package com.xinyan.contorller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class FileController {

    @GetMapping("/getFile")
    public void  getFile(HttpServletResponse response, @RequestParam(defaultValue = "true") boolean isOnline){
        File file = new File("d:/img/草莓.jpeg");
        String name = file.getName();
        System.out.println("isOnline = " + isOnline);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
            if (isOnline){
                // 在线打开方式 文件名应该编码成UTF-8
                System.out.println("inline方式下载");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + URLEncoder.encode(name, "utf-8"));
            }else {
                // 纯下载方式 文件名应该编码成UTF-8
                System.out.println("纯下载方式");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(name, "utf-8"));
            }
            StreamUtils.copy(new BufferedInputStream(new FileInputStream(file)), outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
